/*
 * SerializerFactory.java July 2009
 *
 * Copyright (C) 2009, Quirino Zagarese <quirino@laszloitalia.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 */
package org.eu4ria.serialization;

import java.util.Hashtable;

public class SerializerFactory {

	private Hashtable<String, Serializer> serializersBindings = new Hashtable<String, Serializer>();

	private ArraySerializer arraySerializer = new ArraySerializer();

	private CollectionSerializer collectionSerializer = new CollectionSerializer();

	private AnnotatedObjectSerializer annotatedObjectSerializer = new AnnotatedObjectSerializer();

	private static SerializerFactory instance = null;

	private SerializerFactory(){

	}

	public static SerializerFactory getInstance(){
		if(instance == null){
			instance = new SerializerFactory();
			Serializer serializer = new NumberSerializer();
			instance.addSerializer(Integer.class, serializer);
			instance.addSerializer(Long.class, serializer);
			instance.addSerializer(Float.class, serializer);
			instance.addSerializer(Double.class, serializer);
			instance.addSerializer(int.class, serializer);
			instance.addSerializer(long.class, serializer);
			instance.addSerializer(float.class, serializer);
			instance.addSerializer(double.class, serializer);
			serializer = new VoidSerializer();
			instance.addSerializer(Void.class, serializer);
			instance.addSerializer(void.class, serializer);
			serializer = new StringSerializer();
			instance.addSerializer(String.class, serializer);
			serializer = new BooleanSerializer();
			instance.addSerializer(Boolean.class, serializer);
			instance.addSerializer(boolean.class, serializer);
		}
		return instance;
	}

	public void addSerializer(Class serializableClass, Serializer serializer) {
		serializersBindings.put(serializableClass.getName(), serializer);
	}

	public Serializer getSerializer(Class clazz) {

		if (clazz != null) {
			if (clazz.isArray()) {
				return arraySerializer;
			} else if (java.util.Collection.class.isAssignableFrom(clazz)) {
				return collectionSerializer;
			} else {
				Serializer serializer  = serializersBindings.get(clazz.getName());
				if(serializer != null){
					return serializer;
				}else{
					return annotatedObjectSerializer ;
				}

			}
		}else{
			return null;
		}

	}
}
